package com.network.utils.demo;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.network.monitor.tool.NetworkInterceptor;
import com.network.monitor.tool.NetworkListener;
import com.network.monitor.utils.NetworkTool;
import com.network.retrofit.net.callback.GsonErrorBack;
import com.network.retrofit.net.okhttp.MyLogInterceptor;
import com.network.retrofit.net.okhttp.OkHttpUtil;
import com.network.retrofit.utils.gson.GsonErrorBean;
import com.network.utils.R;
import com.network.utils.demo.api.ApiTest;
import com.network.utils.demo.api.AppUpDataApi;
import com.network.utils.demo.http.ParamsUtil;
import com.network.utils.demo.model.TestModel;
import com.network.retrofit.net.ApiResponse;
import com.network.retrofit.net.RetrofitClient;
import com.network.retrofit.net.RetrofitFileClient;
import com.network.retrofit.net.callback.DownloadCallBack;
import com.network.retrofit.net.file.FileDownService;
import com.network.retrofit.net.http.ResponseThrowable;
import com.network.retrofit.utils.NetWorkBaseUtil;
import com.network.retrofit.utils.NetWorkLogUtil;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends RxAppCompatActivity {
    private Button button1,button2,button3;
    private TestModel testModel;
    private String downFileUrl="http://dldir1.qq.com/qqmi/aphone_p2p/TencentVideo_V6.0.0.14297_848.apk";
    private String savePathDir= Environment.getExternalStorageDirectory()
            + File.separator + "NetWorkTestDown" + File.separator;
    private String saveFileName="QQDown.apk";


    private OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        okHttpClient = new OkHttpClient.Builder()
                .eventListenerFactory(NetworkListener.get())
                .addNetworkInterceptor(new NetworkInterceptor())
                .addNetworkInterceptor(new MyLogInterceptor("OkHttpBack_TAG"))//添加网络库拦截器
                .build();

        init();
        testModel=new TestModel();
        button1=findViewById(R.id.button1);
        button2=findViewById(R.id.button2);
        button3=findViewById(R.id.button3);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testNetWorkCheck();
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testNetWorkCheck2();
                //创建文件夹
                new FileDownService(downFileUrl,savePathDir,saveFileName)
                        .setLifecycleTransformer(MainActivity.this.bindToLifecycle())
                        .setDownloadCallBack(new DownloadCallBack() {
                            @Override
                            public void onProgress(String url, String filePath, int progress) {
                                NetWorkLogUtil.logE("我收到进度",progress);
                                //切换线程  避免在主线程进行下载任务
                                Observable.empty().observeOn(AndroidSchedulers.mainThread()).doOnComplete(() -> {
                                    button2.setText("下载进度:"+progress);
                                }).subscribe();
                            }

                            @Override
                            public void onCompleted(String url, String filePath, long totalLength) {
                                //button2.setText("Action2");
                            }


                            @Override
                            public void onError(String url, String filePath, String msg) {
                                //button2.setText("Action2");
                            }

                            @Override
                            public void onExisted(String url, String filePath) {

                            }
                        }).downFile();

            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testHtmlHttp();
                //RetrofitFileClient.getService().pauseDown(downFileUrl);
            }
        });
    }



    private void init(){
        RetrofitClient.getService()
                .setDebug(true)
                .setBaseUrl("https://ecmapiuat.ysservice.com.cn")
                .init(this.getApplication());

        RetrofitFileClient.getService().init();
        //初始化网络监听
        NetworkTool.getInstance().init(this.getApplication());
        //建议只在debug环境下显示，点击去网络拦截列表页面查看网络请求数据
        NetworkTool.getInstance().setShowFloat();

        NetworkTool.getInstance().addNetInfoListener(data -> {
            NetWorkLogUtil.logE("网络请求结束后的请求内容信息",new Gson().toJson(data.getNetworkFeedBean()));
            NetWorkLogUtil.logE("网络请求结束后的请求时间信息",new Gson().toJson(data.getTimeInfoMap()));
        });

        RetrofitClient.getService().setOkHttpClient(okHttpClient);

        /*String testTrans="{\"type\":\"workorder_abnormity_close_approval_001\",\"messageId\":\"62ac2431a487d80001d576f2\",\"functionId\":\"7a48b488-e15b-41f9-98d8-34a1f5480305\",\"noticeType\":\"2\",\"url\":\"/abnormalApproveDetail?approvalCode=非关&approvalId=7a48b488-e15b-41f9-98d8-34a1f5480305\",\"appid\":\"10008\"}";
        TestBean testBean2=new TestBean();
        testBean2.setUrl("123123");
        testBean2.setAppid("dddddd");
        NetWorkBaseUtil.getInstance().setGsonErrorBack(new GsonErrorBack() {
            @Override
            public void errorBack(GsonErrorBean errorBean) {
             NetWorkLogUtil.logE("GsonErrorBean");
            }
        });
        TestBean testBean=NetWorkBaseUtil.getInstance().transGsonData(testBean2,TestBean.class);
        NetWorkLogUtil.logE("TestBean end");*/

    }

    private void testHttp(){
        testModel.load(this.getApplication(),this.bindToLifecycle());
    }



    private void testHtmlHttp(){
        //String url="http://test.wencaischool.net/openlearning/"+ URLAddress.ME_GET_NEW_VERSION;
        //String url="https://crmtest.ysservice.com.cn/auth/login/internalLogin";
        String url="https://crmtest.ysservice.com.cn/mkf/sync_SyncQuesTask_getQuesRecordListTI.do";
        Map<String, String> params= ParamsUtil.getParams();
        //ParamsUtil.setPublicParam(params,this.getApplication());
        params.put("password","123456");
        params.put("phoneModel","Xiaomi_venus,androidVersion=11,net=WIFI");
        params.put("userName","luodan");
        params.put("version","99");
        params.put("mac","4C:F2:02:E2:79:FC");
        params.put("platform","1");

        Map<String, String> headers= ParamsUtil.getParams();
        headers.put("authToken","ebei_crm");
        headers.put("userId","");
        headers.put("sensorsAnonymousId","f7c57b1ca27fdb11");
        headers.put("fromSystem","staffAPP");
        headers.put("sign","DEC53A1E76705719AAAC520409D6EC5E");
        headers.put("Content-Type","application/json");
        //headers.put("Connection","keep-alive");
        //headers.put("Content-Length","152");
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");

        ParamsUtil.showParam(params);
        ParamsUtil.showParam(headers);
        String body="{\"password\":\"123456\",\"phoneModel\":\"Xiaomi_venus,androidVersion\\u003d11,net\\u003dWIFI\",\"userName\":\"luodan\",\"version\":\"99\",\"mac\":\"4C:F2:02:E2:79:FC\",\"platform\":\"1\"}";

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),NetWorkBaseUtil.getInstance().getGson().toJson(params));

        RetrofitClient.getService().instanceRetrofitGson(AppUpDataApi.class)
                .doPostBody(url,requestBody,headers)
                .compose(RetrofitClient.rxConfig(this.bindToLifecycle()))
        .subscribe(new ApiResponse<Object>() {
            @Override
            public void responseData(Object data) {
                NetWorkLogUtil.logE("MainActivity responseData",data.toString());
                Toast.makeText(MainActivity.this,data.toString(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void responseNull() {

            }

            @Override
            public void netError(ResponseThrowable errorInfo) {
                NetWorkLogUtil.logE("MainActivity netError",errorInfo.getCode()+errorInfo.getMessage());
            }
        });


    }

    private void testHtmlHttp2(){
        //String url="http://test.wencaischool.net/openlearning/"+ URLAddress.ME_GET_NEW_VERSION;
        String url="https://crmtest.ysservice.com.cn/MQTTProxy/redis_Redis_device.do";
        Map<String, String> params= ParamsUtil.getParams();
        params.put("message","{\"userid\":\"luodan\",\"platform\":\"umeng\",\"deviceid\":\"AmuSoWNfvKFVPBVhHR0Q6XYCc62NNV8mlSp-6oe5RnM-\",\"time\":\"2021-07-01 16:45:50\",\"bind\":\"1\",\"dev\":\"0\",\"did\":\"809dcad9cda8a4f466b80d3b29ee7ceb\"}");

        Map<String, String> headers= ParamsUtil.getParams();
        headers.put("authToken","6a6c4eed-c1af-4f12-bc29-7329afb619c2");
        headers.put("userId","537");
        headers.put("sensorsAnonymousId","2d0d683edf60835a");
        headers.put("fromSystem","staffAPP");
        headers.put("sign","BB3D1D6222446248152215685A985DBF");
        headers.put("Content-Type","application/x-www-form-urlencoded");
        //headers.put("Connection","keep-alive");
        //headers.put("Content-Length","285");
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");

        ParamsUtil.showParam(params);
        ParamsUtil.showParam(headers);

        RetrofitClient.getService().instanceRetrofitGson(AppUpDataApi.class)
                .doPost(url,params,headers)
                .compose(RetrofitClient.rxConfig(this.bindToLifecycle()))
                .subscribe(new ApiResponse<Object>() {
                    @Override
                    public void responseData(Object data) {
                        NetWorkLogUtil.logE("MainActivity responseData",data.toString());
                        Toast.makeText(MainActivity.this,data.toString(),Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void responseNull() {

                    }

                    @Override
                    public void netError(ResponseThrowable errorInfo) {
                        NetWorkLogUtil.logE("MainActivity netError",errorInfo.getCode()+errorInfo.getMessage());
                    }
                });

    }

    private void testHtmlHttp3(){
        String url="https://crmtest.ysservice.com.cn/rest/syncBusinessInfo/queryArmIdByCrmId";
        Map<String, String> params= ParamsUtil.getParams();
        //ParamsUtil.setPublicParam(params,this.getApplication());
        params.put("projectId","58727");

        Map<String, String> headers= ParamsUtil.getParams();
        headers.put("authToken","6a6c4eed-c1af-4f12-bc29-7329afb619c2");
        headers.put("userId","537");
        headers.put("sensorsAnonymousId","2d0d683edf60835a");
        headers.put("fromSystem","staffAPP");
        headers.put("sign","E1C6AC1672835B8C58EA5D45C01458E3");
        headers.put("Content-Type","application/x-www-form-urlencoded");
      /*  headers.put("Connection","keep-alive");
        headers.put("Content-Length","15");*/
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");

        ParamsUtil.showParam(params);
        ParamsUtil.showParam(headers);
        RetrofitClient.getService().instanceRetrofitGson(AppUpDataApi.class)
                .doPost(url,params,headers)
                .compose(RetrofitClient.rxConfig(this.bindToLifecycle()))
                .subscribe(new ApiResponse<Object>() {
                    @Override
                    public void responseData(Object data) {
                        NetWorkLogUtil.logE("MainActivity responseData",data.toString());
                    }

                    @Override
                    public void responseNull() {

                    }

                    @Override
                    public void netError(ResponseThrowable errorInfo) {
                        NetWorkLogUtil.logE("MainActivity netError",errorInfo.getCode()+errorInfo.getMessage());
                    }
                });
    }



    private void testHtmlHttp4(){
        //OkHttpClient okHttpClient= OkHttpUtil.getInstance().getOkHttpClient(this.getApplication());
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .eventListenerFactory(NetworkListener.get())
                .addNetworkInterceptor(new NetworkInterceptor())
                .build();

        String url="https://crmtest.ysservice.com.cn/mkf/sync_SyncCommonData_getDictDetailInfoTI.do?dictCode=crmCloseReason";
        RetrofitClient.getService().instanceRetrofit(AppUpDataApi.class,okHttpClient, RetrofitClient.ParmaType.TYPE_XML)
                .doPostXmlTest(url)
                .compose(RetrofitClient.rxConfig(this.bindToLifecycle()))
                .subscribe(new ApiResponse<TaskSourceListBean>() {
                    @Override
                    public void responseData(TaskSourceListBean data) {
                        NetWorkLogUtil.logE("MainActivity responseData",data.toString());
                    }

                    @Override
                    public void responseNull() {

                    }

                    @Override
                    public void netError(ResponseThrowable errorInfo) {
                        NetWorkLogUtil.logE("MainActivity netError",errorInfo.getCode()+errorInfo.getMessage());
                    }
                });




    }


    private void checkID(){
        Map<String, String> params= ParamsUtil.getParams();
        params.put("ImageURL","http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeIdentityCard/sfzbm1.jpg");
        params.put("Side","back");
        params.put("Action","RecognizeIdentityCard");


        String url="https://crmtest.ysservice.com.cn/mkf/sync_SyncCommonData_getDictDetailInfoTI.do?dictCode=crmCloseReason";
        RetrofitClient.getService().instanceRetrofitXml(AppUpDataApi.class)
                .doPostXmlTest(url)
                .compose(RetrofitClient.rxConfig(this.bindToLifecycle()))
                .subscribe(new ApiResponse<TaskSourceListBean>() {
                    @Override
                    public void responseData(TaskSourceListBean data) {
                        NetWorkLogUtil.logE("MainActivity responseData",data.toString());
                    }

                    @Override
                    public void responseNull() {

                    }

                    @Override
                    public void netError(ResponseThrowable errorInfo) {
                        NetWorkLogUtil.logE("MainActivity netError",errorInfo.getCode()+errorInfo.getMessage());
                    }
                });
    }


    private void testNetWorkCheck(){

        HashMap<String, String> params=new HashMap<>();
        params.put("platform_name","永升活");
        params.put("show_channel","1");
        params.put("pageSize","4");
        params.put("page","1");
        params.put("query_type","1");
        params.put("goods_tag_id","37");
        params.put("projectId","58843");
        params.put("city_code","310100");

        String url="https://ecmapiuat.ysservice.com.cn/weixin/goods-tag/list-items-new";
        RetrofitClient.getService().instanceRetrofitGson(ApiTest.class)
                .test(url,params)
                .compose(RetrofitClient.rxConfig(this.bindToLifecycle()))
                .subscribe(new ApiResponse<Object>() {

                    @Override
                    public void responseData(Object data) {
                        NetWorkLogUtil.logE("testNetWorkCheck responseData",data.toString());
                        Toast.makeText(MainActivity.this,data.toString(),Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void responseNull() {

                    }

                    @Override
                    public void netError(ResponseThrowable errorInfo) {

                    }
                });
    }

    private void testNetWorkCheck2(){

        HashMap<String, String> params=new HashMap<>();
     /*   params.put("platform_name","永升活");
        params.put("show_channel","1");
        params.put("pageSize","4");
        params.put("page","1");
        params.put("query_type","1");
        params.put("goods_tag_id","37");
        params.put("projectId","58843");
        params.put("city_code","310100");*/

        String url="https://crm2.ysservice.com.cn/platform-api/app/byAppId/10007";
        RetrofitClient.getService().instanceRetrofitGson(ApiTest.class)
                .test(url,params)
                .compose(RetrofitClient.rxConfig(this.bindToLifecycle()))
                .subscribe(new ApiResponse<Object>() {

                    @Override
                    public void responseData(Object data) {
                        NetWorkLogUtil.logE("testNetWorkCheck responseData",data.toString());
                        Toast.makeText(MainActivity.this,data.toString(),Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void responseNull() {

                    }

                    @Override
                    public void netError(ResponseThrowable errorInfo) {

                    }
                });
    }


    private void testOKhttp(){

        String url="http://test";
        okhttp3.OkHttpClient client=new okhttp3.OkHttpClient();
        Request request=new Request.Builder().url(url).build();

        Call call=client.newCall(request);

        try {
            Response response=call.execute();
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {

                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}